package com.demo.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.demo.gateway.rest.RestInterceptorFactory;

import lombok.Data;

/**
 * @author: demo
 * @date: 2020年6月23日
 * @Document : redis template配置
 */
@Configuration
@Data
public class RestTemplateConfig {

	@Value("${spring.rest.readTimeout:30000}")
	private Integer readTimeout;

	@Value("${spring.rest.connectTimeout:5000}")
	private Integer connectTimeout;

	@Value("${spring.rest.debug:false}")
	private Boolean debug;

	@Autowired
	private RestInterceptorFactory restInterceptorFactory;

	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
		RestTemplate restTemplate = new RestTemplate();
		if (debug) {
			restTemplate.setInterceptors(
					restInterceptorFactory.asRestInterceptors(restInterceptorFactory.getRequestLoggerInterceptor()));
		}
		List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
		converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
		converters.add(new FormHttpMessageConverter());
		converters.add(new ByteArrayHttpMessageConverter());
		converters.add(new MappingJackson2HttpMessageConverter());
		restTemplate.setMessageConverters(converters);
		restTemplate.setRequestFactory(factory);
		return restTemplate;
	}

	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(readTimeout);
		factory.setConnectTimeout(connectTimeout);
		return factory;
	}
}
